import os
import sys
import time
import requests

from release_info import ReleaseInfo


class DLSUpdater:
    # NA_RELEASE_LINK = "https://gitee.com/dlcn/dlsna/releases/latest"
    CQ_RELEASE_LINK = "https://gitee.com/dlcn/dlscq/releases/latest"

    def __init__(self):
        # self.na_latest_info: ReleaseInfo = self.__init_info(self.NA_RELEASE_LINK)
        self.cq_latest_info: ReleaseInfo = self.__init_info(self.CQ_RELEASE_LINK)

    @staticmethod
    def __init_info(link: str) -> ReleaseInfo:
        """发送get请求获取最新发行的标签"""
        try:
            res = requests.get(link, timeout=5).json()
            return ReleaseInfo(res)
        except Exception as e:
            print(f"[ERROR] 获取信息异常：{e}")
            input("[ERROR] 按下Enter退出...")
            sys.exit()

    def print_info(self):
        print(f"[INFO] 当前DLS最新版本有: ")
        # print(f"[1] 『{self.na_latest_info.tag}』 QQ官方接口版本")
        # print(f"{self.na_latest_info.msg}")
        print(f"[WS] 『{self.cq_latest_info.tag}』 onebot接口版本")
        print(f"{self.cq_latest_info.msg}")

    # def select_ver(self) -> ReleaseInfo:
    #     while True:
    #         text = input("输入序号选择一个版本: ")
    #         if text == "1":
    #             return self.na_latest_info
    #         elif text == "2":
    #             return self.cq_latest_info

    def update(self):
        new_file_name = "DLS-new.exe"
        base_file_name = "DLS.exe"
        print("[INFO] 请先关闭正在运行的DLS程序！")
        self.print_info()
        input("[INFO] 按下Enter开始下载...")
        select_info = self.cq_latest_info
        # 下载新文件
        try:
            start_time = time.time()
            res = requests.get(select_info.file_link, stream=True)
            total_size = int(res.headers.get('content-length', 0))
            # 开始下载并显示进度
            with open(new_file_name, "wb") as f:
                now_size = 0
                for data in res.iter_content(1024):
                    now_size += len(data)
                    f.write(data)
                    print(f"\r[INFO] 文件下载中: "
                          f"{now_size // 1024}KB/{total_size // 1024}KB", end="")
                print("")
            end_time = time.time()
            print(f"[INFO] 文件下载完毕！耗时{round(end_time - start_time, 1)}s")
        except requests.exceptions.MissingSchema:
            print(f"[ERROR] 未找到更新文件！")
            input("[ERROR] 按下Enter退出...")
            sys.exit()
        except Exception as e:
            print(f"[ERROR] 下载文件时发生异常：{type(e)}")
            input("[ERROR] 按下Enter退出...")
            sys.exit()
        # 移除旧文件
        try:
            print("[INFO] 尝试删除旧版本的DLS程序")
            if os.path.exists(base_file_name):
                os.remove(base_file_name)
        except Exception as e:
            print(f"[ERROR] 删除文件时发生异常：{e}")
            input("[ERROR] 请尝试手动删除旧文件并重命名新文件")
            sys.exit()
        # 重命名新文件
        try:
            os.rename(new_file_name, base_file_name)
        except Exception as e:
            print(f"[INFO] 重命名文件发生错误：{e}")
        input("[INFO] 更新程序完成！按下Enter退出...")
        sys.exit()
